use std::io::{self, Write};
use std::process::Command;
use std::process::Stdio;

fn execute_command(input: &str) {
    let parts: Vec<&str> = input.trim().split_whitespace().collect();
    if parts.is_empty() {
        return;
    }

    match Command::new(parts[0]).args(&parts[1..]).spawn() {
        Ok(mut child) => {
            child.wait().expect("命令执行失败");
        }
        Err(e) => {
            eprintln!("错误: {}", e);
        }
    }
}

fn parse_command(input: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current_part = String::new();
    let mut in_quotes = false;
    let mut escape = false;

    for c in input.chars() {
        if escape {
            current_part.push(c);
            escape = false;
            continue;
        }

        match c {
            '\\' => escape = true,
            '"' => in_quotes = !in_quotes,
            ' ' if !in_quotes => {
                if !current_part.is_empty() {
                    parts.push(current_part);
                    current_part = String::new();
                }
            }
            _ => current_part.push(c),
        }
    }

    if !current_part.is_empty() {
        parts.push(current_part);
    }

    parts
}

fn handle_pipeline(input: &str) -> io::Result<()> {
    let commands: Vec<&str> = input.split('|').map(|s| s.trim()).collect();
    if commands.len() < 2 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "管道需要至少两个命令",
        ));
    }

    let mut previous_output = None;

    for (i, cmd) in commands.iter().enumerate() {
        let parts = parse_command(cmd);
        if parts.is_empty() {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "空命令"));
        }

        let mut command = Command::new(&parts[0]);
        if parts.len() > 1 {
            command.args(&parts[1..]);
        }

        if i == 0 {
            command.stdout(Stdio::piped());
        } else if i == commands.len() - 1 {
            if let Some(prev_out) = previous_output {
                command.stdin(prev_out);
            }
        } else {
            if let Some(prev_out) = previous_output {
                command.stdin(prev_out);
            }
            command.stdout(Stdio::piped());
        }

        let child = command.spawn()?;
        previous_output = child.stdout;
    }

    Ok(())
}

fn main() {
    println!("欢迎使用 Rust Shell (rshell)");
    println!("输入 'exit' 退出");

    loop {
        print_prompt();
        let input = read_input();

        if input.trim() == "exit" {
            break;
        }

        println!("你输入了: {}", input);
    }
}

fn print_prompt() {
    print!("rshell> ");
    io::stdout().flush().expect("刷新 stdout 失败");
}

fn read_input() -> String {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("读取输入失败");
    input
}